package com.yn.module.spider.config.strategy;

import com.yn.module.spider.utils.base.BaseSpiderService;
import com.yn.module.spider.utils.constant.Const;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 策略模式factory，用来存储service上对应的配置信息
 * @author: 叶甯
 * @create: 2022/7/28 14:31
 * @since: 1.0.0
 * @copyright (C), 2022, https://gitee.com/johnny .All rights reserved.
 */
@Component
public class StrategyFactory implements ApplicationContextAware {

    /**
     * 获取爬虫相关策略信息
     *
     * @param dto
     * @return
     */
    public static SpiderDTO getStrategy4Spider(SpiderDTO dto) {
        return SPIDER_FACTORY.get(dto.type().value() + Const.DEFAULT_SPLIT + dto.svc().value());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // spider相关
        Map<String, Object> importMap = applicationContext
                .getBeansWithAnnotation(SpiderConfig.class);
        for (Map.Entry<String, Object> entry : importMap.entrySet()) {
            Class<BaseSpiderService> handleClz = (Class<BaseSpiderService>) entry.getValue().getClass();
            SpiderConfig strategy = handleClz.getAnnotation(SpiderConfig.class);
            SpiderDTO entity = new SpiderDTO()
                    .currentService(applicationContext.getBean(handleClz))
                    .type(strategy.type())
                    .svc(strategy.svc());
            SPIDER_FACTORY.put(strategy.type().value() + Const.DEFAULT_SPLIT + strategy.svc().value(), entity);

        }
    }

    /**
     * 用来存储消息的factory
     */
    private static Map<String, SpiderDTO> SPIDER_FACTORY = new HashMap<>();

}
